import { CrudOptions, AddReq, DelReq, EditReq, dict, CrudExpose, compute, UserPageQuery, CreateCrudOptionsRet, CreateCrudOptionsProps, ScopeContext} from '@fast-crud/fast-crud';
import * as _ from 'lodash-es';
import * as api from './api';
import { request } from '/@/utils/service';
import { dictionary } from '/@/utils/dictionary';
import {inject} from "vue";


// 注释编号:django-vue3-admin__crud400716:这里服务器账号的子表进来
import subTableComponent from "../SrvAccountViewSet/SubSrvAccountViewSet/index.vue";
import { fa } from 'element-plus/es/locale';

// 注释编号:django-vue3-admin-crud355117:代码开始行
// 功能说明:导入多选批量删除需求
import XEUtils from 'xe-utils';
import { nextTick, ref } from 'vue';


//此处为crudOptions配置
export default function (object: CreateCrudOptionsProps): CreateCrudOptionsRet {
	
	const {crudRef } = object.crudExpose;
	const { crudExpose } = object;

	const pageRequest = async (query: any) => {
		return await api.GetList(query);
	};
	const editRequest = async ({ form, row }: EditReq) => {
		if (row.id) {  
			form.id = row.id;
		}
		return await api.UpdateObj(form);
	};
	const delRequest = async ({ row }: DelReq) => {
		return await api.DelObj(row.id);
	};
	const addRequest = async ({ form }: AddReq) => {
		return await api.AddObj(form);
	};

    const exportRequest = async (query: UserPageQuery) => {
		return await api.exportData(query)
	};

		// 注释编号:django-vue3-admin-crud402311:代码开始行
		// 功能说明:配置选中行的功能
		
		//记录选中的行
		const selectedRows = ref<any>([]);

		const onSelectionChange = (changed: any) => {
			const tableData = crudExpose.getTableData();
			const unChanged = tableData.filter((row: any) => !changed.includes(row));
			// 添加已选择的行
			XEUtils.arrayEach(changed, (item: any) => {
				const ids = XEUtils.pluck(selectedRows.value, 'id');
				if (!ids.includes(item.id)) {
					selectedRows.value = XEUtils.union(selectedRows.value, [item]);
				}
			});
			// 剔除未选择的行
			XEUtils.arrayEach(unChanged, (unItem: any) => {
				selectedRows.value = XEUtils.remove(selectedRows.value, (item: any) => item.id !== unItem.id);
			});
		};
		const toggleRowSelection = () => {
			// 多选后，回显默认勾选
			const tableRef = crudExpose.getBaseTableRef();
			const tableData = crudExpose.getTableData();
			const selected = XEUtils.filter(tableData, (item: any) => {
				const ids = XEUtils.pluck(selectedRows.value, 'id');
				return ids.includes(item.id);
			});
	
			nextTick(() => {
				XEUtils.arrayEach(selected, (item) => {
					tableRef.toggleRowSelection(item, true);
				});
			});
		};

		// 注释编号:django-vue3-admin-crud402311:代码结束行


	return {
		// 注释编号:django-vue3-admin-crud565217:代码开始行
		// 功能说明:这里要配置return，不然crudExpose获取不到
		selectedRows,
		toggleRowSelection,
		// 注释编号:django-vue3-admin-crud565217:代码结束行


		crudOptions: {
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			actionbar: {
				buttons: {
					export:{
                        click(){
                            return exportRequest(crudExpose.getSearchFormData())
                        }
					},
				}
			},
			form: {
				col: { span: 8 },
				// // labelWidth: '100px',
				wrapper: {
					is: 'el-dialog',
					width: '1200px',
				},
				group: {
					groups: {
						base: {
							slots: {
								label: () => { return (<span style={{ color: "blue" }}>基本信息</span>);}
							},
							columns: [ "name", "vmid", "vmhost", "hostname", "domain", "service_class", "ipaddress", "vmtool", "vmdatastore", "os_type", "os_version", "backup_ip", "cpu_cores", "mem_size", "disk_size", "nics", "disk_num", "sub_ipaddress" ]
						},
						manage: {
							slots: {
								label: () => { return (<span style={{ color: "blue" }}>管理信息</span>);}
							},
							columns: [ "owner_func", "owner_leader", "owner", "form_online", "form_offline", "remark", "subTable" ]
						},
					},
				},
			},
			viewForm: {
				wrapper: {
					buttons: {
						ok: { show: false },
						cancel: { show: false },
						reset: { show: false },
					},
				},
			},
			search: {
				container: {
					layout: "multi-line"
				},
				col: {
					span: 4
				},
				options: {
					// labelWidth: "100px"
				}
			},
			table: {
				rowKey: 'id', //设置你的主键id， 默认rowKey=id
				onSelectionChange,
				onRefreshed: () => toggleRowSelection(),   // 注释编号:django-vue3-admin-crud255417:需要配置toggleRowSelection
				// size: "small",
			},
			columns: {
				// 注释编号:django-vue3-admin-crud260511:代码开始行
				// 功能说明:要配置出来$checked
				$checked: {
					title: "选择",
					form: { show: false },
					column: {
						type: "selection",
						align: 'center',
						width: '40px',  // 注释编号:django-vue3-admin-crud340311:这个宽度你要按照自己的页面为调整，不然会出现一个display: inline-flex，导致无法居中显示
						columnSetDisabled: true, //禁止在列设置中选择
					}
				},
				// 注释编号:django-vue3-admin-crud260511:代码结束行
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '55px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				},
				id: {
					title: 'ID',
					type: 'number',
					column: { show: false },
					search: { show: false },
					form: { show: false },
				},
				name: {
					title: 'VM名称',
					type: 'input',
					search: { show: true},
					column: {
						minWidth: 230,
						sortable: 'custom',
					},
					form: {
						rules: [{ required: true, message: 'VM名称名必填' }],
						component: {
							placeholder: '请输入VM名称',
						},
					},
				},
				vmid: {
					title: 'VM编号',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				service_class: {
					title: '服务类型',
					search: { show: false },
					type: 'dict-select',
					dict: dict({
						url: '/api/ServiceClassViewSet/?limit=999',
						value: 'id',
						label: 'title',
						getData: async ({ url }: { url: string }) => {
							return request({
								url: url,
							}).then((ret: any) => {
								return ret.data;
							});
						},
					}),
					column: {
						width: 110, //最小列宽
						sortable: 'custom',
						// fixed:true,
					},
					form:{
						component:{},
					},
				},
				hostname: {
					title: '主机名',
					type: 'input',
					search: { show: true },
					column: {
						minWidth: 180,
						sortable: 'custom',
					},
					form:{
						component:{},
					},
				},
				ipaddress: {
					title: 'IP地址',
					type: 'input',
					search: { show: true },
					column: {
						minWidth: 120,
						sortable: 'custom',
					},
					form: { 
						helper: '请输入IP地址格式如192.168.1.1',
						rules: [{ pattern:/^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$/, message: '格式如192.168.1.1或255.255.255.0'}],
						component:{},
					},
				},
				vmhost: {
					title: '宿主机',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				vmtool: {
					title: 'Tool状态',
					type: 'input',
					search: { show: false },
					column: { 
						minWidth: 130,
						sortable: 'custom',
					 },
					form:{
						component:{},
					},
				},
				vmdatastore: {
					title: '数据存储',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				nics: {
					title: '网卡数量',
					type: 'number',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				disk_num: {
					title: '硬盘数量',
					type:'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				domain: {
					title: '域名',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				os_type: {
					title: 'OS类别',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				os_version: {
					title: 'OS版本',
					type: 'input',
					search: { show: true },
					column: { 
						minWidth: 260,
						sortable: 'custom',
					 },
					form:{
						component:{},
					},
				},
				backup_ip: {
					title: '备份IP',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form: { 
						helper: '请输入IP地址格式如192.168.1.1',
						rules: [{ pattern:/^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$/, message: '格式如192.168.1.1或255.255.255.0'}],
					},
				},
				sub_ipaddress: {
					title: '子IP地址',
					type: [ "textarea", "colspan" ],
					search: { 
						show: true, 
						component: {
							placeholder: ' ',
						}
					},
					column: { 
						ellipsis: true,  // 列显示时如果内容过长，将会显示省略号
						minWidth: 200,
      					showTitle: true // 鼠标悬浮在省略号上时，显示完整内容
					 },
					form: { 
						helper: '多个IP地址以逗号分隔',
						component: {
						}
					},
				},
				cpu_cores: {
					title: 'CPU核数',
					type: 'number',
					search: { show: false },
					column: { 
						width: 100,
					 },
					 form:{
						component:{},
					},
				},
				mem_size: {
					title: '内存容量',
					type: 'number',
					search: { show: false },
					column: { 
						width: 100,
					},
					form:{
						component:{},
					},
				},
				disk_size: {
					title: '硬盘容量',
					type: 'number',
					search: { show: false },
					column: { 
						width: 100,
					},
				},
				update_datetime: {
					title: '更新时间',
					type: 'datePicker',
					search: { show: false },
					column: { 
						minWidth: 160,
						sortable: 'custom',
					},
					form:{ show: false },
				},
				is_vm: {
					title: '是否虚拟机',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form: { 
						value: 'true',
						show: false,
					 },
				},
				owner_func: {
					title: '归属部门',
					type: 'input',
					search: { show: true },
					column: { 
						width: 120,
					 },
					form:{
						component:{},
					},
				},
				owner: {
					title: '管理员',
					type: 'input',
					search: { show: true },
					column: { 
						minWidth: 240,
					},
					form:{
						component:{},
					},
				},
				owner_leader: {
					title: '管理主管',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				}, 
				form_online: {
					title: '上架单号',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				form_offline: {
					title: '下架单号',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				remark: {
					title: '备注',
					type: [ "textarea", "colspan" ],
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				// 注释编号:django-vue3-admin-crud514816:代码开始行
				// 功能说明:由这个subTable字段来引用相应子表进来
				subTable: {
					title: "账号",
					type: "text",
					form: {
						title: "",  //配置在form内没有title内容
						labelWidth:"0",   //配置子表的宽度占满介面
						component: {
						name: subTableComponent,
						id:compute(({form})=>{
							return form.id
						}),
						on:{
							//可以传进form进去async saveMain({form})
							async saveMain(){
							//保存主表
							const formRef = crudExpose.getFormRef()
							const ret = await formRef.submit()
							//将form改为编辑模式
							let formWrapperRef = crudExpose.getFormWrapperRef();
							// 这个地方要改为拿到ret.res.data，示例中拿到的是ret.res,如果没有拿到值，会出现无法把值传过去窗口，或者传他认为那是一个新的对象
							//如果这里三行代码出现问题，都有可能会导致保存之后，再保存会出现新的对象
							formWrapperRef.setFormData(ret.res.data)
							crudRef.value.formWrapperRef.formOptions.mode = "edit"
							crudRef.value.formWrapperRef.title="编辑"
							}
						}
						},
						col: {
						span: 24
						},
					},
					column: {
						width: 120,
						formatter: ({ row }) => {
						return "限查看或编辑";
						}
					}
					},
				// 注释编号:django-vue3-admin-crud514816:代码结束行
			},
		},
	};
}
